package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class JavaSerializable {
    /**
     * 持久化对象
     *
     * @param obj
     * @param out
     * @throws IOException
     */
    public void store(Object obj, OutputStream out) throws IOException
    {
        ObjectOutputStream outputStream = new ObjectOutputStream(out);
        outputStream.writeObject(obj);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 加载对象
     *
     * @param in
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public Object load(InputStream in) throws IOException,
            ClassNotFoundException
    {
        ObjectInputStream inputStream = new ObjectInputStream(in);
        Object obj = inputStream.readObject();
        inputStream.close();
        return obj;
    }

    public static void main(String[] args) throws Exception
    {
        String storeName = "java object";

        JavaSerializable serializable = new JavaSerializable();

        File file = new File("file.dat");
        serializable.store(storeName, new FileOutputStream(file));
        System.out.println(serializable.load(new FileInputStream(file)));
    }

}
